import pymysql


def main():
    # 1、创建连接对象
    conn = pymysql.connect(host='106.15.205.83', port=3306,
                           user='kfx1997', password='1234QWEasd',
                           db='school', charset='utf8')
    try:
        # 2、获取游标对象
        with conn.cursor() as cursor:  # with ... as ... 上下文语法, 结束自动关闭, with open 一样
            # 3、执行SQL得到的结果
            # cursor.execute(SQL语句) # 返回结果是一个int, 受影响的行
            # 1)insert
            result = cursor.execute('insert into tb_student values (1, "孔庆雷", 1, now())')

            # 2)update
            # result = cursor.execute('update tb_student set stusex={0} where stuname="{1}"'.format(0, '孔庆雷'))

            # 3)delete
            # result = cursor.execute('delete from tb_student where stuid=%s', (1, ))
            if result == 1:
                print('成功')
            print(result)
            # 4、操作成功执行提交
            conn.commit()
    except pymysql.MySQLError as error:
        print(error)
        # 4、操作失败执行回滚
        conn.rollback()
    finally:
        # 5、关闭连接，释放资源，没有上下文语法的支持
        conn.close()


if __name__ == '__main__':
    main()
